package com.zhuiyun.project.api.system.login.controller;

import com.zhuiyun.project.api.system.login.service.impl.SysPermissionService;
import com.zhuiyun.project.api.system.menu.entity.SysMenu;
import com.zhuiyun.project.api.system.menu.service.SysMenuService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @ClassName SysLoginController
 * @Description TODO
 * @Author lzy
 * @Date 2023/6/16 13:55
 **/
@RestController
public class SysLoginController {


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysMenuService menuService;

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public CommonResult getInfo() throws IOException {
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return CommonResult.ok(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public CommonResult getRouters() {
        Integer userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return CommonResult.ok(menuService.buildMenus(menus));
    }

}
